// 购物车

import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./user";
import { insertCartAPI, findNewCartList,delCartAPI } from "@/apis/cart";

export const useCartStore = defineStore('cart', () => {

    // 判断登录逻辑
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)

    // 1.定义state
    const cartList = ref([])
    // 2.定义action
    const addCart = async (good) => {
        const {skuId, count} = good
        if(isLogin.value){
            // 登录之后加入购物车
            await insertCartAPI({skuId, count})
            updateNewCartList()
        }else{
            // 添加到购物车操作
            // 已添加过，++
            // 未添加过，直接push
            const item = cartList.value.find((item) => good.skuId === item.skuId)
            if(item){
                // 已添加
                item.count++
            }else {
                // 未添加
                cartList.value.push(good)
            }
        }
        
    }

    // 删除购物车
    const delCart = async (skuId) => {
        if(isLogin.value){
            // 登录之后加入购物车
            await delCartAPI([skuId])
            updateNewCartList()
        }else{
            const index = cartList.value.findIndex((item) => skuId === item.skuId)
            cartList.value.splice(index, 1)
        }
    }

    // 封装公共代码块
    const updateNewCartList = async () => {
        const res = await findNewCartList()
        cartList.value = res.result
    }

    // 购物车总数和总价的计算属性
    // 1.计算总数
    const allCount = computed(() => cartList.value.reduce((a, c) =>a + c.count , 0))
    // 2.计算总价
    const allPrice = computed(() => cartList.value.reduce((a, c) =>a + c.count * c.price , 0))

    // 购物车列表复选框
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }

    // 所有列表被选中时为全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))

    // 全选或取消全选
    const selectAll = (selected) => {
        cartList.value.forEach(item => item.selected = selected)
    }

    // 购物车列表所选中的总数和总价
    // 选中总数
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + 1 , 0))
    // 选中总价
    const selectedTotalPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price , 0))

    // 清空购物车
    const clearCart = () => {
        cartList.value = []
    }

    return {
        cartList,
        allCount,
        allPrice,
        isAll,
        selectedCount,
        selectedTotalPrice,
        addCart,
        delCart,
        singleCheck,
        selectAll,
        clearCart,
        updateNewCartList
    }
},
{
    persist: true
}
)